<template>
  <div class="login">
    <el-card>
      <h3>系统登录</h3>
      <el-form :model="form" label-width="120px" :rules="rules" status-icon>
        <el-form-item label="用户名" prop="username">
          <el-input
            type="input"
            v-model="form.username"
            autocomplete="off"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="form.password"
            autocomplete="off"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login" class="login-button"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getCurrentInstance, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
export default {
  setup() {
    const router = useRouter();
    const { proxy } = getCurrentInstance();
    const store = useStore();
    let form = reactive({
      username: "",
      password: "",
    });
    const rules = ref({
      username: [
        { required: true, message: "请输入用户名", trigger: "blur" },
        { min: 3, message: "用户名长度不能小于3位", trigger: "blur" },
      ],
      password: [{ required: true, message: "请输入密码", trigger: "blur" }],
    });
    const login = async () => {
      if (form.username === "" || form.password === "") {
        proxy.$message.error("请输入用户名和密码");
        return;
      }
      const res = await proxy.$api.getMenu(form);
      store.commit("setToken", res.token);
      store.commit("setUserLabel", form.username);
      store.commit("setMenu", res.menu);
      store.commit("addMenu", router);
      router.push({ name: "home" });
      proxy.$message.success("登录成功");
    };
    return { form, rules, login };
  },
};
</script>

<style lang="less" scoped>
.el-card {
  width: 450px;
  position: absolute;
  top: 30%;
  left: 50%;
  transform: translate(-50%, -50%);
  h3 {
    text-align: center;
  }
  .login-button {
    margin-left: 75px;
  }
}
</style>
